<template>
  <div class="common-container">
    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-wrapper">
        <!-- 左侧操作按钮 -->
        <div class="left-operations">
          <el-button
            type="danger"
            :disabled="!hasSelected"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
          <el-button
            type="success"
            @click="handleExport"
            style="display: none;"
          >
            <el-icon><Download /></el-icon> 导出数据
          </el-button>
          <el-button
            type="primary"
            @click="handleRefresh"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>

        <!-- 右侧搜索区域 -->
        <div class="right-search">
          <el-form :inline="true" :model="searchForm" @submit.prevent class="search-form">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="date-picker"
              />
            </el-form-item>
            <el-form-item label="关键词">
              <el-input
                v-model="searchForm.keyword"
                placeholder="输入关键词搜索"
                clearable
                @keyup.enter="handleSearch"
                @input="handleKeywordChange"
                class="keyword-input"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="records"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        border
        highlight-current-row
      >
        <el-table-column type="selection" width="55" fixed="left" />

        <el-table-column
          label="用户信息"
          width="200"
        >
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-name">
                {{row.user?.display_name }}({{ row.user?.username }})
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="查询内容"
          prop="query_content"
          min-width="200"
        >
          <template #default="{ row }">
            <div class="content-cell">
              <span class="query-content">{{ row.message || row.query_content }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="系统回复"
          min-width="200"
        >
          <template #default="{ row }">
            <div class="content-cell">
              <div v-if="row.system_replies && row.system_replies.length">
                <span class="response-content">{{ row.system_replies[0].message }}</span>
                <el-tag v-if="row.system_replies.length > 1" size="small" type="info">
                  共{{ row.system_replies.length }}条回复
                </el-tag>
              </div>
              <span v-else class="no-response">暂无回复</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="查询时间"
          prop="timestamp"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatTimestamp(row.timestamp) }}
          </template>
        </el-table-column>

        <el-table-column
          label="会话名称"
          width="120"
        >
          <template #default="{ row }">
            <el-tag size="small">{{ row.session.session_title || '未知会话' }}</el-tag>
          </template>
        </el-table-column>




        <el-table-column
          label="操作"
          width="120"
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                  size="small"
                  type="primary"
                  circle
                  @click="handleViewDetail(row)"
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  size="small"
                  type="danger"
                  circle
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageInfo.current"
          v-model:page-size="pageInfo.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加标签对话框 -->
    <el-dialog
      title="添加标签"
      v-model="showTagDialog"
      width="400px"
    >
      <el-form :model="tagForm" @submit.prevent>
        <el-form-item label="标签名称">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showTagDialog = false">取消</el-button>
          <el-button type="primary" @click="handleTagSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElIcon,
  ElCard,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElPagination,
  ElTag,
  ElTooltip,
  ElMessage,
  ElMessageBox,
  ElEmpty
} from 'element-plus'
import {
  Plus,
  Delete,
  Download,
  Refresh,
  View,
  Search,
} from '@element-plus/icons-vue'
import { useQueryRecordStore } from '@/stores/queryRecord'
import { formatTimestamp } from '@/utils/queryDataProcessor'
import { ignoreError } from '@/utils/errorHandling'
import { debounce } from '@/utils/performance'

// Router
const router = useRouter()

// Store
const recordStore = useQueryRecordStore()

// 选择相关状态
const hasSelected = computed(() => recordStore.selectedRecordIds.length > 0)

// 表格状态
const loading = computed(() => recordStore.loading)
const records = computed(() => recordStore.records)

// 分页相关变量
const pageInfo = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  dateRange: []
})

// 优化搜索 - 添加防抖
const debouncedSearch = debounce(() => {
  pageInfo.current = 1
  fetchRecords()
}, 500)

// 搜索相关函数
const handleSearch = () => {
  debouncedSearch()
}

// 关键词输入时防抖搜索
const handleKeywordChange = () => {
  if (searchForm.keyword.trim() === '') {
    handleSearch()
  } else {
    debouncedSearch()
  }
}

// 标签表单
const showTagDialog = ref(false)
const tagForm = reactive({
  name: '',
  recordId: null
})

// 方法：表格操作
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    const descending = order === 'descending'
    recordStore.setSorting(prop, descending)
  }
}

const handleSelectionChange = (selection) => {
  recordStore.selectedRecordIds = selection.map(item => item.id)
}

// 方法：查看详情
const handleViewDetail = (row) => {
  router.push({ name: 'RecordDetail', params: { id: row.id } })
}

// 方法：批量删除操作
const handleBatchDelete = () => {
  if (!recordStore.selectedRecordIds.length) {
    ElMessage.warning('请先选择记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${recordStore.selectedRecordIds.length} 条记录吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    recordStore.batchDeleteRecords(recordStore.selectedRecordIds)
  }).catch(() => {})
}

// 方法：导出操作
const handleExport = () => {
  ElMessage.info('导出功能正在开发中')
}

// 其他UI辅助函数
const getModelTagType = (modelType) => {
  if (!modelType) return ''

  if (modelType.includes('gpt-3')) return 'success'
  if (modelType.includes('gpt-4')) return 'primary'
  if (modelType.includes('claude')) return 'warning'

  return 'info'
}

const getStatusTagType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'failed': return 'danger'
    case 'in_progress': return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'failed': return '失败'
    case 'in_progress': return '处理中'
    default: return '未知'
  }
}

// 页面加载
onMounted(async () => {
  await fetchRecords()
})

// 删除函数
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除此会话记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    await ignoreError(recordStore.deleteRecord)(row.id)
    ElMessage.success('删除成功')
    fetchRecords()
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 搜索相关函数
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.dateRange = []
  handleSearch()
}

// 处理标签相关函数
const handleTagSubmit = () => {
  if (!tagForm.name.trim()) {
    ElMessage.warning('标签名称不能为空')
    return
  }

  // 找到当前记录
  const recordIndex = records.value.findIndex(r => r.id === tagForm.recordId)
  if (recordIndex === -1) return

  const record = records.value[recordIndex]
  const tags = [...record.tags, tagForm.name]

  // 保存标签
  ignoreError(recordStore.updateRecordTags)(record.id, tags)

  // 更新本地数据
  records.value[recordIndex].tags = tags

  showTagDialog.value = false
  tagForm.name = ''
  ElMessage.success('添加标签成功')
}

// 分页函数
const handleSizeChange = (val) => {
  pageInfo.size = val
  fetchRecords()
}

const handleCurrentChange = (val) => {
  pageInfo.current = val
  fetchRecords()
}

// 刷新功能
const handleRefresh = () => {
  fetchRecords()
}

// 获取记录函数 - 添加缓存和错误处理
const fetchRecords = async (showLoading = true) => {
  // 避免重复请求
  if (loading.value && showLoading) return

  if (showLoading) {
    loading.value = true
  }

  try {
    const params = {
      page: pageInfo.current,
      page_size: pageInfo.size,
      keyword: searchForm.keyword?.trim() || '',
      start_date: searchForm.dateRange?.[0] || '',
      end_date: searchForm.dateRange?.[1] || ''
    }

    // 使用缓存key
    const cacheKey = JSON.stringify(params)

    const data = await recordStore.getAdminMessages(params)
    recordStore.records = data.data || []
    pageInfo.total = data.total || 0
  } catch (error) {
    console.error('获取记录失败:', error)
    ElMessage.error('获取记录失败，请稍后重试')
  } finally {
    if (showLoading) {
      loading.value = false
    }
  }
}

// 定义组件名称
defineOptions({
  name: 'RecordsList'
})
</script>

<style scoped>
.el-form-item--default{
  margin-bottom: 0px !important;
}

.common-container {
  padding: 20px;
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.operation-card {
  margin-bottom: 15px;
  flex-shrink: 0;
}

.operation-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.right-search {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-end;
}

.date-picker {
  width: 300px;
}

.keyword-input {
  width: 220px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 14px;
  display: flex;
  flex-direction: column;
}

.user-id {
  font-size: 12px;
  color: #909399;
}

.content-cell {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.query-content {
  font-size: 14px;
  color: #333;
}

.response-content {
  font-size: 14px;
  color: #409EFF;
}

.no-response {
  font-size: 13px;
  color: #909399;
  font-style: italic;
}

.message-badge {
  position: absolute;
  top: 0;
  right: 8px;
  transform: translateY(-50%);
}

.tags-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin-right: 4px;
}

.add-tag-btn {
  margin-left: 2px;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}
</style>
